#include "initializationtask.h"
#include "libs/core/model/livemodel.h"
#include "libs/core/model/model.h"
#include "liveplatforms/douyin.h"
#include "liveplatforms/kuaishou.h"
#include "services/yingceservice.h"
#include "storage/localstorage.h"
#include "yingce.h"
#include <QFile>
#include <QtDebug>

InitializationTask::InitializationTask(QObject* parent) : yc::Task { 300000, parent } { }

void InitializationTask::startImpl()
{
    YingCeService::instance()->getAllPlatforms(
            yc::ResponseHandler(this, &InitializationTask::onGetAllPlatforms));
}

void InitializationTask::onTimeout()
{
    loadLocalData();
}

void InitializationTask::onGetAllPlatforms(const yc::Request& request, const yc::Response& response)
{
    if (response.status() == yc::OK_CODE) {
        const auto ja = response.data().toArray();
        if (ja.empty()) {
            loadLocalData();
            Q_EMIT finished();
        } else {
            for (const auto i : ja) {
                const auto jo = i.toObject();
                platforms_.push_back(Platform { jo["id"].toInt(), jo["version"].toInt() });
            }
            pos_ = -1;
            getPlatform();
        }
    } else {
        loadLocalData();
        Q_EMIT finished();
    }
}

void InitializationTask::onGetPlatform(const yc::Request& request, const yc::Response& response)
{
    Q_UNUSED(request)
    if (response.status() == yc::OK_CODE) {
        const auto jo = response.data().toObject();
        const auto code = jo["code"].toString();
        const auto ba = QByteArray::fromHex(code.toLatin1());
        const auto ba2 = qUncompress(ba);
        const auto raw_code = QString::fromUtf8(ba2);
        const yc::LiveWebEntry entry {
            jo["id"].toInt(),     jo["name"].toString(),
            jo["url"].toString(), jo["profileUrl"].toString(),
            jo["ua"].toInt(),     yc::WebScript { jo["point"].toInt(), raw_code },
            jo["version"].toInt()
        };
        LocalStorage::instance().liveWebEntryDAO()->insert(entry);
        YingCe::instance()->model()->liveModel()->addWebEntry(entry);
    } else {
        const auto entry =
                LocalStorage::instance().liveWebEntryDAO()->getByPlatform(platforms_.at(pos_).id);
        if (entry.platform != yc::UNKNOWN_PLATFORM_TYPE) {
            YingCe::instance()->model()->liveModel()->addWebEntry(entry);
        }
    }
    getPlatform();
}

void InitializationTask::loadLocalData()
{
    auto lm = YingCe::instance()->model()->liveModel();
    const auto entries = LocalStorage::instance().liveWebEntryDAO()->getAll();
    if (entries.empty()) {
        // 添加直播平台的直播入口
        lm->setWebEntries(QList<yc::LiveWebEntry> { DouYin::webEntry(), KuaiShou::webEntry() });
    } else {
        lm->setWebEntries(entries);
    }
}

void InitializationTask::getPlatform()
{
    if (++pos_ >= platforms_.size()) {
        Q_EMIT finished();
    } else {
        const auto& platform = platforms_.at(pos_);
        auto dao = LocalStorage::instance().liveWebEntryDAO();
        int version = dao->getVersionByPlatform(platform.id);
        if (version < platform.version) {
            YingCeService::instance()->getLiveWebEntry(
                    platform.id, yc::ResponseHandler(this, &InitializationTask::onGetPlatform));
        } else {
            YingCe::instance()->model()->liveModel()->addWebEntry(dao->getByPlatform(platform.id));
            getPlatform();
        }
    }
}
